import gevent.monkey
gevent.monkey.patch_all()

import multiprocessing
import os

# 绑定地址和端口
bind = '0.0.0.0:8181'

# 监听队列最大长度
backlog = 512

# 超时时间，适当延长以适应 SSE 长连接
timeout = 300

# 使用 gevent 作为工作类
worker_class = 'gevent'

# 根据 CPU 核心数设置工作进程数量
workers = multiprocessing.cpu_count() * 2 + 1

# 每个工作进程的线程数
threads = 1

# 日志级别
loglevel = 'info'

# 访问日志格式
access_log_format = '%(t)s%(p)s%(h)s"%(r)s"%(s)s%(L)s%(b)s%(f)s""%(a)s'

# 访问日志文件路径
accesslog = "./logs/gunicorn_access.log"

# 错误日志文件路径
errorlog = "./logs/gunicorn_error.log"

# SSL 证书和私钥文件路径，根据实际情况修改
# certfile = './ssl/cert.pem'
# keyfile = './ssl/privkey.pem'

def when_ready(server):
    from django.core.management import call_command
    call_command('check')

def pre_fork(server, worker):
    from django.db import connections
    for conn in connections.all():
        conn.close_if_unusable_or_obsolete()

def pre_exec(server):
    server.log.info("Forked child, re-executing.")

def post_fork(server, worker):
    from django.db import connections
    connections.close_all()

def child_exit(server, worker):
    from django.db import connections
    connections.close_all()